package com.hktry.ioc;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 *
 * @version 1.0
 * @author hktry
 * @Email 13117011726@163.com Descriptions： ApplicationContext.java Company：
 *        浙江祥生物业服务有限公司
 * @date 2017年3月6日
 */
public class ApplicationContext {
	private String backPackage;

	private BeanScan beanScan = new BeanScan();

	private final Map<Class, BeanFactory> beanFactorys = new HashMap<>();

	private final Map<String, Object> map = new HashMap<>();

	public ApplicationContext(String baskPackage) throws ClassNotFoundException {
		this.backPackage = baskPackage;
		init();
	}

	private void init() throws ClassNotFoundException {
		beanScan.scan(backPackage);
		for (String clasName : beanScan.getList()) {
			Class cls = Class.forName(clasName);
			Bean c = (Bean) cls.getAnnotation(Bean.class);
			if (c != null) {
				String key = c.value();
				BeanFactory bf = new SimpleBeanFactory(cls);
				beanFactorys.put(cls, bf);
				map.put(key, bf.getBean());
			}
		}
		for (Entry<Class, BeanFactory> entry : beanFactorys.entrySet()) {
			entry.getValue().setProperties(map);
		}

	}

	public Object getBean(String beanName) {
		return map.get(beanName);
	}

}
